package com.green.common.util;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.green.common.weibo4j.org.json.JSONArray;
import com.green.common.weibo4j.org.json.JSONException;
import com.green.common.weibo4j.org.json.JSONObject;

/**
 * 宇展盈讯http接口
 * @author Administrator
 *
 */
public class HttpSmsUtil {
	
	public static String userName = "yp-80"; // 接口账号
	public static String password = "123456"; // 密码
	public static String sign = "【世华经纪】"; // 短信签名，该签名必须提前报备
	public static String subcode = ""; // 扩展字号
	public static String sendtime = ""; // 定时发送时间，时间格式201305051230
	public static String url = "http://sms.shwsms.com/httpInterfaceSubmitAction.do"; // 无限通使用地址
	public static String url_report = "http://sms.shwsms.com/httpDeliverAction.do"; // 无限通使用地址


	// MD5 加密函数
	public static String MD5Encode(String sourceString) {
		String resultString = null;
		try {
			resultString = new String(sourceString);
			MessageDigest md = MessageDigest.getInstance("MD5");
			resultString = byte2hexString(md.digest(resultString.getBytes()));
		} catch (Exception ex) {
		}
		return resultString;
	}

	public static final String byte2hexString(byte[] bytes) {
		StringBuffer bf = new StringBuffer(bytes.length * 2);
		for (int i = 0; i < bytes.length; i++) {
			if ((bytes[i] & 0xff) < 0x10) {
				bf.append("0");
			}
			bf.append(Long.toString(bytes[i] & 0xff, 16));
		}
		return bf.toString();
	}

	/**
	 * 短信发送
	 * 
	 * @param msgid
	 *            自定义msgid，用户查询发送结果
	 * @param phone
	 *            发送号码(小于等于500)
	 * @param content
	 *            发送内容
	 */
	public static String send(String phone,
			String content) {
		String posturl = url;
		Map<String, String> params = new LinkedHashMap<String, String>();
		
		params.put("account", userName);
		params.put("password", MD5Encode(password));
		params.put("mobile", phone);
		params.put("content", content);
		
		String resp = doPost(posturl, params);
		return resp;
	}

	/**
	 * 获取发送状态报告
	 * 
	 * @return 返回状态报告map
	 */
	public static String getReport() {
		String posturl = url_report;
		Map<String, String> params = new LinkedHashMap<String, String>();
		params.put("account", userName);
		params.put("password", MD5Encode(password));
		String resp = doPost(posturl, params);
		System.out.println(resp);
		System.out.println("######################");
		return resp;
	}





	/**
	 * 执行一个HTTP POST 请求，返回请求响应的HTML
	 * 
	 * @param url
	 *            请求的URL 地址
	 * @param params
	 *            请求的查询参数,可以为null
	 * @return 返回请求响应的HTML
	 */
	private static String doPost(String url, Map<String, String> params) {
		String response = null;
		HttpClient client = new HttpClient();
		PostMethod postMethod = new PostMethod(url);
		postMethod.getParams().setParameter(
				HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
		// 设置Post 数据
		if (!params.isEmpty()) {
			int i = 0;
			NameValuePair[] data = new NameValuePair[params.size()];
			for (Entry<String, String> entry : params.entrySet()) {
				data[i] = new NameValuePair(entry.getKey(), entry.getValue());
				i++;
			}
			postMethod.setRequestBody(data);
		}
		try {
			client.executeMethod(postMethod);
			if (postMethod.getStatusCode() == HttpStatus.SC_OK) {
				response = postMethod.getResponseBodyAsString();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			postMethod.releaseConnection();
		}
		return response;
	}


	
  /**
  *    111
18676665381;110804561939535;3;2013-11-08 17:12:58
18688976041;110804561939535;3;2013-11-08 17:12:57
  * @param args
  */
	public static void main(String[] args) {

     //send("18676665381,18688976041","尊敬的客户：海岸城超大2居室。");
	  List<Map<String,Object>> resultList=new ArrayList<Map<String,Object>>();
	  Map<String,Object> tempMap=null;
	  String[] tempStr=null;
	  
	  String returnStr=getReport();
	
	  
	  if(null!=returnStr && returnStr.startsWith("111")){
		  
		 
		  String[] str=returnStr.split("\n");
		  
		  
		  if(str.length>1){
			  
			  for(int i=1;i<str.length;i++){
				  
				  tempMap=new HashMap<String,Object>();
				  tempStr=str[i].split(";");
				  
				  tempMap.put("phone", tempStr[0]);
				  tempMap.put("msgid",tempStr[1]);
				  tempMap.put("status",tempStr[2]);
				  resultList.add(tempMap);			  
			  }
			  System.out.println(resultList.size());
		  }else{
			  System.out.println("请求成功，没有数据！");
		  }
		  
	  }
	}
}